<?php
declare (strict_types=1);

namespace app\common\controller;

use app\model\Img;
use app\Request;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\Image;

class CommonHander extends ServerResponse
{
    //图片上传方法
    public function upload(Request $request)
    {
        $file = $request->file('file');
        $type = $request->post('type')??''; //表示文章上传图片，前端任意传，不用type做判断
        try {
            validate([
                'file' => [
                    // 限制文件大小(单位b)，这里限制为4M
//                    'fileSize' => 4 * 1024 * 1024,
                    // 限制文件后缀，多个后缀以英文逗号分割
                    'fileExt' => 'gif,jpg,png,jpeg'
                ]
            ])->check(['file' => $file]);
            $save = Filesystem::disk('photo')->putFile('photo', $file);
            $path = str_replace('\\', '/', '/uploads/' . $save);
            // 打开图片
            $image = Image::open(public_path() . $path);
            // 生成缩略图
            if($type==''){
                $image->thumb(150, 150)->save(public_path() . $path);
            }else{
                $image->thumb(250,250)->save(public_path() . $path);
            }
            $temporary_url = $path;
            $data=Img::create(['url'=>$path]);
            if($data){
                return ServerResponse::jsonData(1, '上传成功', ['url' => DOMAIN_NAME . $path, "temporary_url" => $temporary_url]);
            }else{
                return ServerResponse::jsonData(0, '上传失败',null);
            }
        } catch (ValidateException $e) {
            return ServerResponse::jsonData(0, $e->getMessage(), null);
        }
    }

//    图片删除
    public function imageDel(Request $request)
    {
        $file = $request->post('file');
        $file_url='../public'.$file;
        if(file_exists($file_url)){
            if(unlink($file_url)){
                $data=Img::where('url','=',$file)->delete();
                if($data){
                    return ServerResponse::jsonData(1, '删除成功!', $file_url);
                }else{
                    return ServerResponse::jsonData(0, '删除失败!', $file_url);
                }
            }else{
                return ServerResponse::jsonData(0, '删除失败!', null);
            }
        }else{
            return ServerResponse::jsonData(0, '路径不存在!', $file_url);
        }
    }
    //文件上传
    public function uploadFile(Request $request){
        $file = $request->file('file');
        $type = $request->post('type')??''; //表示文章上传图片，前端任意传，不用type做判断
        $save = Filesystem::disk('photo')->putFile('file', $file);
        $path = str_replace('\\', '/', '/uploads/' . $save);
        $temporary_url = public_path() . $path;
        return ServerResponse::jsonData(1, '上传成功', ['url' => DOMAIN_NAME . $path, "temporary_url" => $temporary_url]);
    }
    //文件删除
    public function fileDel(Request $request){

    }
}
